﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.BLL;
using ZX.BLL.Extend;
using ZX.DBModule;
using System.Data;
using DevExpress.XtraReports.UI;
using System.Drawing;

namespace ZX.WebApp.Reports
{
    public partial class ReportView : BasePage
    {
        private int length=0;
        private string[] _field = null;
        private float[] _colWidth = null;
        private string _strEntity = string.Empty;
        private string _strTable = string.Empty;
        private Guid _functionID = Guid.Empty; //所属
        private string _reportName = string.Empty;
        private string _condition = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            _strEntity = GetStringFromQueryString("entity", "");
            _functionID = GetGuidFromQueryString("fid");
            _condition = GetStringFromQueryString("condition", "");
            SysReport report = new SysReport();
            CreateBussniess(_strEntity);
            if (_bll == null)
            {
                _bll = new BaseBussnies();
                _bll.entity = report;
                _condition = (_condition == "") ? _bll.GetRoleCondition(this.User, _strEntity, _functionID) : "(" + _bll.GetRoleCondition(this.User, _strEntity, _functionID)+") and ("+_condition+")";
            }
            ///获取报表文件
            report = _bll.GetEntityByCondition<SysReport>("EntityName='" + _strEntity + "'");
            if (report == null)
            {
                Response.Write("没有报表");
                return;
            }

            DevExpress.XtraReports.UI.XtraReport rpt ;
            //rpt = DevExpress.XtraReports.UI.XtraReport.FromFile(Server.MapPath("\\upload\\"+report.ReportFile), true);


            string _ReportTemplate = System.IO.File.ReadAllText(Server.MapPath("\\upload\\"+report.ReportFile));
            //.Replace("{2}",BuildReportCellInfo(_list,"0")).Replace("{3}",BuildReportCellCtrl(_list,"1")).Replace("{4}",(_list,"1")).Replace("{5}",(_list,"1"));
            //读取流程
            //this.Response.Write(_ReportTemplate.ToString());
            Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(_ReportTemplate);

            rpt = DevExpress.XtraReports.UI.XtraReport.FromStream(new System.IO.MemoryStream(bytes), true);

            //rpt = DevExpress.XtraReports.UI.XtraReport(Server.MapPath("\\upload\\" + report.ReportFile), true);
          
            ////获取字段名
            InitDetailCol(rpt);
           
            //获取表名
            BaseEntity entity = ZX.Common.Globals.getEntity(_strEntity) as BaseEntity;
            _strTable = (entity == null ? _strEntity : entity.GetTableName());

            CreateReport(rpt);
            ReportViewer1.Report = rpt;
        }

        private void InitReportHeaderTitle(DevExpress.XtraReports.UI.XtraReport rpt, SysReport report)
        {
            DevExpress.XtraReports.UI.XRLabel ctrl = rpt.FindControl("THeaderTitle", true) as DevExpress.XtraReports.UI.XRLabel;
            if (ctrl.Text.Length == 0)
            {
                ctrl.Text = report.ReportName;
            }
        }

        private void InitDetailCol(DevExpress.XtraReports.UI.XtraReport rpt)
        {
            DevExpress.XtraReports.UI.XRTable ctrl = rpt.FindControl("TDetail", true) as DevExpress.XtraReports.UI.XRTable;
            length = ctrl.Rows[0].Cells.Count;
            _field = new string[length];
            _colWidth = new float[length];
            for (int i = 0; i < length; i++)
            {
                _field[i] = ctrl.Rows[0].Cells[i].Tag.ToString();
                _colWidth[i] = ctrl.Rows[0].Cells[i].WidthF;
                var cell = ctrl.Rows[0].Cells[0];
            }
        }

        private void CreateReport(XtraReport rpt)
        {
            FillDataSource(rpt);
            rpt.DataMember = ((DataSet)rpt.DataSource).Tables[0].TableName;
            InitBands(rpt);//添加带区（Bands）
            InitStyles(rpt);//添加Styles
            InitDetailsBasedonXRTable(rpt);//用XRTable显示报表
            //rpt.ShowPreviewDialog();
        }

        public void FillDataSource(XtraReport rpt)
        {
            string _order = GetStringFromQueryString("order","");
            _order = _order == "" ? "" : " order by " + _order;
            rpt.DataSource = new ZX.DAL.DBExtend.DbSql().Query(string.Format("select * from {0} {1} {2}", _strTable, _condition == "" ? "" : " where " + _condition, _order));
        }

        public void InitBands(XtraReport rpt)
        {
            DetailBand detail = new DetailBand();
            rpt.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { detail});
        }


        public void InitStyles(XtraReport rep)
        {
            XRControlStyle oddStyle = new XRControlStyle();
            XRControlStyle evenStyle = new XRControlStyle();

            oddStyle.BackColor = Color.LightBlue;
            oddStyle.StyleUsing.UseBackColor = true;
            oddStyle.StyleUsing.UseBorders = false;
            oddStyle.Name = "OddStyle";

            evenStyle.BackColor = Color.LightPink;
            evenStyle.StyleUsing.UseBackColor = true;
            evenStyle.StyleUsing.UseBorders = false;
            evenStyle.Name = "EvenStyle";

            rep.StyleSheet.AddRange(new DevExpress.XtraReports.UI.XRControlStyle[] { oddStyle, evenStyle });
        }

        public void InitDetailsBasedonXRTable(XtraReport rpt)
        {
            DataSet ds = ((DataSet)rpt.DataSource);

            DevExpress.XtraReports.UI.XRTable _tableDetail = rpt.FindControl("TDetail", true) as DevExpress.XtraReports.UI.XRTable;
            XRTable tableDetail = rpt.FindControl("table1", true) as DevExpress.XtraReports.UI.XRTable;

            XRTableRow detailRow = tableDetail.Rows[0];

            tableDetail.Rows.Add(detailRow);
            tableDetail.EvenStyleName = "EvenStyle";
            tableDetail.OddStyleName = "OddStyle";


            //{
            for (int i = 0; i < length; i++)
            {

                XRTableCell detailCell = detailRow.Cells[i];
                detailCell.WidthF = _colWidth[i];
                //detailCell.DataBindings.Add("Text", null, ds.Tables[0].Columns[i].Caption);
                detailCell.DataBindings.Add("Text", null, _field[i]);
                if (i == 0)
                {
                    //headerCell.Borders = DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top | DevExpress.XtraPrinting.BorderSide.Bottom;
                    detailCell.Borders = DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top | DevExpress.XtraPrinting.BorderSide.Bottom;
                }
                else
                {
                    //headerCell.Borders = DevExpress.XtraPrinting.BorderSide.All;
                    detailCell.Borders = DevExpress.XtraPrinting.BorderSide.All;
                }

                // Place the cells into the corresponding tables
                //headerRow.Cells.Add(headerCell);
                detailRow.Cells.Add(detailCell);
            }

            // Place the table onto a report's Detail band
                //rpt.Bands[BandKind.PageHeader].Controls.Add(tableHeader);
            rpt.Bands[BandKind.Detail].Controls.Add(tableDetail);
        }
    }
}